<template>
	<view class="image-drag-sort">
		<view class="inner">
			<movable-area class="movable-area">
				<view class="item" :style="{ 'margin-right': index == list.length - 1 ? '0' : parentStyle, }"
					style="background-color: #ccc" v-for="(item, index) in lists" :key="index" @click="imageTap(index)"
					@longpress="longtap" @touchend="touchend" @touchmove.stop="touchm">
					<image class="img" :src="imgHeader(resizeImage(item))" mode="aspectFill"></image>
					<image class="priview" src="/static/images/preview.png"></image>
				</view>
				<view class="img-upload-btn item"
					:style="{ 'margin-right': parentStyle, 'marginLeft': list.length ? '16rpx' : 0 }"
					@click="imageUpload" v-if="lists.length < max && !active && !disabled">
					<image src="/static/images/camera.png"></image>
					<view>{{ tips }}</view>
					<!-- <text class="text">添加新图片</text> -->
				</view>
				<movable-view class="movable-view" :x="x" :y="y" direction="all" damping="5000" friction="1"
					v-show="active">
					<view class="item-move" :class="{ 'item-move-active': active }">
						<image class="img" :src="imgHeader(resizeImage(lists[beginIndex]))" mode="aspectFill"></image>
					</view>
				</movable-view>
			</movable-area>
		</view>
		<!-- <view class="prompt">点击预览/删除图片，长按拖拽排序，共{{ lists.length }}张图片</view> -->
		<uni-popup ref="popup" :mask-click="false" type="bottom"
			v-if="orderType === 1 && lists.length < max && !active && !disabled">
			<view class="bottomPop">
				<view class="bottomPop_item" @click="takePhoto">
					拍照
					<view class="tips">
						<view>公用梯请拍摄电梯使用证</view>
						<view>私用梯请拍摄控制柜铭牌</view>
					</view>
				</view>
				<view class="cancle flex" @click="() => {
					$refs.popup.close();
				}
					">取消</view>
			</view>
		</uni-popup>
	</view>
</template>
<script>
import unipopup from '@/components/uni-popup/uni-popup';

import { mapState } from 'vuex';
let wrapW = 0, // 拖拽范围的总宽度
	wrapH = 0, // 拖拽范围的总高度
	wrapW2 = 0, // 可拖拽区域宽度
	wrapH2 = 0, // 可拖拽区域高度
	wrapTop = 0, // 拖拽范围的上边界坐标
	wrapLeft = 0, // 拖拽范围的左边界坐标
	wrapDragTop = 0, // 可拖拽范围的上边界坐标
	wrapDragLeft = 0, // 可拖拽范围的左边界坐标
	itemW = 0, // 拖拽元素的宽
	itemH = 0, // 拖拽元素的高
	itemXNun = 0; // 拖拽元素的列数
export default {
	name: 'image-drag-sort',
	components: {
		unipopup,
	},
	data() {
		return {
			resize:{width: 64, height: 64},
			lists: this.list,
			imgIndex: 0,
			active: false, // 是否拖拽状态
			flag: false, // 是否可拖拽
			x: 0,
			y: 0,
			beginIndex: null, // 当前拖拽元素的索引
		};
	},
	props: {
		bindId: {
			// 绑定部件id参数
			type: [String, Number],
			default: '',
		},
		uploadrecord: {
			type: Boolean,
			default: true,
		},
		parentStyle: {
			type: String,
			default: '20rpx',
		},
		// 不可编辑
		disabled: {
			type: Boolean,
			default: false,
		},
		tips: {
			type: String,
			default: '点击拍照',
		},
		padding: {
			type: String,
			default: '30rpx',
		},
		list: {
			type: Array,
			default: function () {
				return [];
			},
		},
		uploadType: {
			// 1两者都有 2只给拍照 3只给选择相册
			type: String,
			default: '1',
		},
		keyName: {
			type: String,
			default: '',
		},
		max: {
			type: Number,
			default: 9,
		},
		imgdel: {
			type: Boolean,
			default: false,
		},
		// 订单类型 默认为0使用默认uni.showActionSheet，如果1自定义
		orderType: {
			type: Number,
			default: 0,
		},
	},
	computed: {
		...mapState('user', ['userinfo']),
		imgList() {
			// console.log('lists', this.list);
			return this.list;
		},
	},
	mounted() {
		let l = this.lists.length;
		if (l) {
			// 有图片时初始化
			this.init();
		}
	},
	beforeDestroy() {
		uni.$off('uploadImg');
	},

	methods: {
		resizeImage(imageUrl) {
			if (!imageUrl) {
				return '';
			}
			if (imageUrl.indexOf('http') == -1) {
				return imageUrl;
			}
			let params = {};
			if (this.resize && this.resize.width && this.resize.height) {
				params.resize = `w_${this.resize.width},h_${this.resize.height}`;
			} else if (this.resize && this.resize.width) {
				params.resize = `w_${this.resize.width}`;
			} else if (this.resize && this.resize.height) {
				params.resize = `h_${this.resize.height}`;
			}
			return this.generateOssImageUrl(imageUrl, params);
		},
		init() {
			// 初始化数据
			// 设置拖拽区域信息
			let wrap = uni.createSelectorQuery().in(this).select('.inner');
			wrap
				.boundingClientRect((data) => {
					// console.log(data)
					wrapW = data.width; // 设置拖拽范围的总宽度
					wrapH = data.height; // 设置拖拽范围的总高度
					wrapTop = data.top; // 设置拖拽范围的上边界坐标
					wrapLeft = data.left; // 设置拖拽范围的左边界坐标
					this.setNodeWH();
				})
				.exec();
		},
		setNodeWH() {
			// 设置拖拽元素的宽高
			// 获取拽拖元素的信息
			let item = uni.createSelectorQuery().in(this).select('.item');
			item
				.boundingClientRect((data) => {
					// console.log(data)
					itemW = data.width; // 拖拽元素的宽度
					itemH = data.height; // 拖拽元素的高度
					this.setDragData();
				})
				.exec();
		},
		setDragData() {
			// 设置拖拽区域及元素配置
			wrapDragTop = wrapTop + itemH / 2; // 设置拖拽范围上边距
			wrapDragLeft = wrapLeft + itemW / 2; // 设置可拖拽范围左边距
			wrapW2 = wrapW - itemW; // 设置可拖拽区域宽度
			wrapH2 = wrapH - itemH; // 设置可拖拽区域高度
			itemXNun = Math.round(wrapW / itemW) - 1; // 设置拖拽元素的列数
		},
		longtap(e) {
			// 长按
			const left = e.currentTarget.offsetLeft,
				top = e.currentTarget.offsetTop;
			this.beginIndex = this.computationIndex({ left: left, top: top }); // 获取所在位置索引
			this.x = left;
			this.y = top;
			this.active = true;
			this.flag = true;
		},
		computationIndex(e) {
			// 计算元素索引
			const left = e.left,
				top = e.top;
			let index = 0, // 计算拖拽元素所在的索引位置
				x = Math.round(left / itemW), // 计算拖拽元素所在的横向索引位置
				y = Math.round(top / itemH), // 计算拖拽元素所在的纵向索引位置
				num = itemXNun * y;
			if (x && !y) {
				// 第一行
				index = x;
			}
			if (y) {
				// 第一行以下
				index = x + y + num;
			}
			return index;
		},
		touchm(e) {
			// 拖拽过程
			if (this.flag) {
				let x = e.touches[0].pageX - wrapDragLeft,
					y = e.touches[0].pageY - wrapDragTop;
				if (x < 0) {
					x = 0;
				}
				if (x > wrapW2) {
					x = wrapW2;
				}
				if (y < 0) {
					y = 0;
				}
				if (y > wrapH2) {
					y = wrapH2;
				}
				this.x = x;
				this.y = y;
			}
		},
		touchend(e) {
			// 拖拽结束
			this.active = false;
			const left = e.currentTarget.offsetLeft,
				top = e.currentTarget.offsetTop;
			if (!this.flag || (this.x === left && this.y === top)) {
				return;
			}
			const x = this.x, // 计算拖拽横向距离
				y = this.y, // 计算拖拽纵向距离
				itemNum = this.lists.length - 1; // 拖拽元素的总数量
			let endIndex = this.computationIndex({ left: x, top: y }); // 获取所在位置索引
			if (endIndex > itemNum) {
				endIndex = itemNum;
			}
			// 交换位置
			const beginIndex = this.beginIndex; // 当前拖拽元素索引
			let data = this.lists,
				tem = data[beginIndex];
			data[beginIndex] = data[endIndex];
			data[endIndex] = tem;
			this.flag = false;

			this.changeArray(this.lists);
		},
		imageTap(i) {
			if (this.disabled) {
				this.previewImage(i);
				return;
			}
			let _this = this;
			this.imgIndex = i;
			// 图片点击事件
			uni.showActionSheet({
				itemList: ['查看大图', '重新上传', '重新拍照', '删除照片'],
				success(res) {
					if (res.tapIndex == 0) {
						// 预览
						_this.previewImage(i);
					} else if (res.tapIndex == 1) {
						// 重新从相册上传
						_this.reLoadImageAlbum(i);
					} else if (res.tapIndex == 2) {
						// 重新拍照
						_this.reLoadImage(i);
					} else if (res.tapIndex == 3) {
						// 删除
						_this.imageDel(i);
					}
				},
			});
		},
		previewImage(i) {
			// 预览图片
			this.$previewMedia({
				current: i,
				sources: this.lists,
			});
		},
		imageDel(i) {
			let _this = this;
			uni.showModal({
				content: '确定要删除该照片吗？',
				cancelText: '否',
				confirmText: '是',
				success(res) {
					if (res.confirm) {
						// 删除图片事件
						_this.lists.splice(i, 1);
						if (_this.imgdel) {
							_this.$emit('imgDels', i);
						} else {
							_this.changeArray(_this.lists);
						}
					}
				},
			});
		},

		imageUpload() {
			if (this.uploadType == '1') {
				let itemList = ['拍照上传', '从相册选择'];
				uni.showActionSheet({
					itemList: itemList,
					success: (res) => {
						this.chooseImage(res.tapIndex);
					},
				});
			} else if (this.uploadType == '2') {
				if (this.orderType === 1) {
					this.$refs.popup.open();
					// this.$emit('chooseUploadType')
				} else {
					this.chooseImage(0);
				}
			} else if (this.uploadType == '3') {
				this.chooseImage(1);
			}
		},
		toCameraPage() {
			let pages = getCurrentPages();
			let pag = pages[pages.length - 1];

			// 设置缓存
			let data = {
				buildingId: '',
				buildingName: '',
				elevatorId: '',
				elevatorAddress: '',
				planId: '',
				planWorkItemId: '',
				partsId: '',
			};
			let imgType = '';
			if (pag.route == 'subpages/repair/repariDetail') {
				imgType = 4;
				try {
					data.buildingId = pag.data.elevatorDetail.buildingId;
					data.buildingName = pag.data.elevatorDetail.buildingName;
					data.elevatorId = pag.data.elevatorDetail.elevatorId;
					data.elevatorAddress = pag.data.elevatorDetail.elevatorAddress;
					data.planId = pag.data.planId;
					data.partsId = this.bindId;
				} catch (error) { }
			}
			if (pag.route == 'subpages/workOrders/partOrder') {
				imgType = 7;
				try {
					data.buildingId = pag.data.eleInfo.buildingId;
					data.buildingName = pag.data.eleInfo.buildingName;
					data.elevatorId = pag.data.eleInfo.id;
					data.elevatorAddress = pag.data.eleInfo.elevatorAddress;
					data.planId = pag.data.planId;
					data.partsId = this.bindId;
				} catch (error) { }
			}

			uni.setStorage({
				key: 'waterMarkMsg',
				data,
				success: (success) => {
					let pages = getCurrentPages();
					let pag = pages[pages.length - 1];
					if (pag.route && pag.route.indexOf('workOrders/detail') != -1) {
						uni.$emit('openCamera', { imgType: imgType || '' });
					} else {
						uni.navigateTo({
							url: '/pages/camera/camera' + (imgType ? '?imgType=' + imgType : ''),
							fail: (err) => {
								console.log(err);
							},
						});
					}
				},
			});
		},
		// 重新从相册上传照片
		reLoadImageAlbum(i) {
			let data = this.lists;

			// #ifndef H5
			uni.chooseImage({
				count: 1,
				sizeType: ['original'], // ['original', 'compressed']
				sourceType: ['album'],
				success: (res) => {
					uni.showLoading({
						title: '上传中',
						mask: true
					});
					this.upload(res.tempFilePaths);
					data.splice(i, 1);
					this.lists = data;
					this.changeArray(this.lists);
					uni.hideLoading();
				},
			});
			// #endif

			// #ifdef H5
			window.sida.chooseImage({
				count: 1,
				sizeType: ['original'], // ['original', 'compressed']
				sourceType: ['album'],
				success: (res) => {
					uni.showLoading({
						title: '上传中',
						mask: true
					});
					this.upload(res.tempFilePaths);
					data.splice(i, 1);
					this.lists = data;
					this.changeArray(this.lists);
					uni.hideLoading();
				},
			});
			// #endif
		},
		// 重新拍照
		reLoadImage(i) {
			let _this = this;

			try {
				uni.$off('uploadImg');
			} catch (error) {
				console.log(error);
			}
			uni.$once('uploadImg', (path, imgId, options) => {
				uni.showLoading({
					title: '上传中',
					mask: true
				});
				let data = _this.lists;
				_this.http
					.upload(path, imgId, options)
					.then((res) => {
						data.splice(i, 1, res.data.link);
						_this.lists = data;
						_this.changeArray(this.lists);

						uni.hideLoading();
					})
					.catch((err) => {
						uni.hideLoading();
					});
			});
			this.toCameraPage();
			return;
		},
		//
		chooseImage(index, i) {
			let _this = this;
			// 选择图片
			let count = this.max - this.lists.length,
				sourceType = index > 0 ? 'album' : 'camera';
			if (sourceType == 'camera') {
				try {
					uni.$off('uploadImg');
				} catch (error) { }
				uni.$once('uploadImg', (path,imgId, options) => {
					uni.showLoading({
						title: '上传中',
						mask: true
					});
					this.upload([path],imgId, options);
				});
				this.toCameraPage();
				return;
			}

			// #ifndef H5
			uni.chooseImage({
				count: count,
				sizeType: ['original'], // ['original', 'compressed']
				sourceType: [sourceType],
				success: (res) => {
					uni.showLoading({
						title: '上传中',
						mask: true
					});
					this.upload(res.tempFilePaths);
				},
				fail: (fail) => {
					console.log('chooseImage', fail);
				},
			});
			// #endif

			// #ifdef H5
			window.sida.chooseImage({
				count: count,
				sizeType: ['original'], // ['original', 'compressed']
				sourceType: [sourceType],
				success: res => {
					uni.showLoading({
						title: '上传中',
						mask: true
					});
					this.upload(res.tempFilePaths);
				}
			});
			// #endif      
		},
		async upload(e,imgId, options) {
			// 可多图上传，不需要的可改成单一上传

			// console.log(e)
			let data = this.lists;
			for (let i = 0, l = e.length; i < l; i++) {
				await this.http
					.upload(e[i],imgId, options)
					.then((res) => {
						data.push(res.data.link);
					})
					.catch((err) => {
						console.log('errors', err);
					});
			}
			this.lists = data;
			this.changeArray(this.lists);

			/* 定位上报埋点*/
			//  this.reportAddress({
			//   longitude: localInfo.longitude,
			//   latitude: localInfo.latitude,
			//   userId: this.userinfo.user_id,
			//   operation: 5,
			//   planId: this.planId,
			//   recordType: 1//提交
			// })
			/* 定位上报埋点 end*/

			uni.hideLoading();
			// 可写上传图片方法或者将本地图片路径传给父组件
		},

		changeArray(list) {
			try {
				let pages = getCurrentPages();
				let pag = pages[pages.length - 1];
				if (pag.data && pag.data.planId && this.uploadrecord) {
					/* 定位上报埋点*/
					// this.reportAddress({
					//   userId: this.userinfo.user_id,
					//   operation: 4,
					//   planId: pag.data.planId,
					//   recordType: 1, //
					// });
					/* 定位上报埋点 end*/
				}
			} catch (error) { }

			this.$emit('changeList', list, this.keyName);
		},
		takePhoto() {
			this.$refs.popup.close();
			this.chooseImage(0);
		},
	},
	watch: {
		list() {
			this.lists = this.list;
			// 监听数组变化
			let l = this.list.length;
			if (l) {
				// 有图片或图片数量改变时重新初始化
				this.init();
			}
		},
	},
};
</script>

<style lang="scss" scoped>
.img {
	width: 100%;
	height: 100%;
}

.image-drag-sort {
	width: 100%;
	box-sizing: border-box;
}

.movable-area {
	width: 100%;
	height: auto;
	display: flex;

	flex-flow: wrap;
}

.item {
	width: 128rpx;
	height: 128rpx;
	/* flex: 0 0 31%; */
	position: relative;
	overflow: hidden;
	// border-radius: 12upx;
}

.priview {
	position: absolute;
	bottom: 10rpx;
	right: 10rpx;
	width: 40rpx;
	height: 40rpx;
	z-index: 2;
}

.item {
	margin-right: 20rpx;
	margin-bottom: 20rpx;
}

// .item:nth-child(n + 4) {
// 	// margin-top: 30rpx;
// }

.img-upload-btn {
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	background-color: #fff;
	// border: 1rpx solid #e0e0e0;
	background-color: #f7f7f8;
	flex-wrap: wrap;
	color: $theme-color;
	font-size: 24rpx;

	image {
		width: 40rpx;
		height: 40rpx;
	}

	view {
		width: 100%;
		text-align: center;
		font-weight: 400;
	}
}

.img-upload-btn .icon {
	width: 48upx;
	height: 48upx;
}

.img-upload-btn .text {
	font-size: 24upx;
	color: #cccccc;
	margin-top: 10upx;
}

.movable-view {
	width: 130rpx;
	height: 130rpx;
	z-index: 33;
}

.item-move {
	width: 100%;
	height: 100%;
	overflow: hidden;
	// border-radius: 12upx;
}

.item-move-active {
	box-shadow: 0 0 30px #000;
}

.prompt {
	font-size: 24upx;
	line-height: 40upx;
	color: #999;
	margin-top: 28upx;
}

.bottomPop {
	background-color: #f2f2f2;

	.bottomPop_item {
		height: 162rpx;
		background: #ffffff;
		border-radius: 24rpx 24rpx 0rpx 0rpx;
		margin-bottom: 16rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;

		.tips {
			color: #0091ff;
			font-size: 24rpx;
		}
	}

	.cancle {
		height: 108rpx;
		background: #ffffff;
	}
}
</style>
